package com.yanchangapp.ui.activity.purchase.contract;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.luck.picture.lib.tools.ScreenUtils;
import com.yanchangapp.R;
import com.yanchangapp.adapter.ContractCommentAdapter;
import com.yanchangapp.adapter.PsDetailCommentAdapter;
import com.yanchangapp.adapter.PsDetailProductAdapter;
import com.yanchangapp.commom.ContractStatus;
import com.yanchangapp.commom.LoadingType;
import com.yanchangapp.commom.OrderStatus;
import com.yanchangapp.model.bean.ContractCommentBean;
import com.yanchangapp.model.bean.OrderCommentBean;
import com.yanchangapp.model.bean.OrderProductBean;
import com.yanchangapp.model.response.ContractDetailResponse;
import com.yanchangapp.ui.presenter.ContractDetailAtPresenter;
import com.yanchangapp.ui.view.ContractDetailAtView;
import com.yanchangapp.widget.SpannableMoney;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.formatter.BigDecimalUtils;
import com.zxl.baselib.util.time.TimeUtil;
import com.zxl.baselib.util.ui.ResHelper;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.util.window.DisplayHelper;
import com.zxl.baselib.widget.NiceNestedScrollView;
import com.zxl.baselib.widget.YCLoadingView;
import com.zyyoona7.popup.EasyPopup;
import com.zyyoona7.popup.XGravity;
import com.zyyoona7.popup.YGravity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 合同详情页
 *
 * 设置右上角menu是否显示...
 *
 * todo 显示详情数据包括列表等
 */
public class ContractDetailActivity extends BaseActivity<ContractDetailAtView, ContractDetailAtPresenter> implements ContractDetailAtView {

    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.ibAddMenu)
    ImageButton ibAddMenu;
    @BindView(R.id.tvProductSum)
    TextView tvProductSum;
    @BindView(R.id.bottom)
    LinearLayout bottom;
    @BindView(R.id.tvTag)
    TextView tvTag;
    @BindView(R.id.tvTextSingleName)
    TextView tvTextSingleName;
    @BindView(R.id.userHead)
    RelativeLayout userHead;
    @BindView(R.id.tvUserDept)
    TextView tvUserDept;
    @BindView(R.id.tvCreateTime)
    TextView tvCreateTime;
    @BindView(R.id.tvOrderContractTitle)
    TextView tvOrderContractTitle;
    @BindView(R.id.tvOrderContract)
    TextView tvOrderContract;
    @BindView(R.id.tvBuyerTitle)
    TextView tvBuyerTitle;
    @BindView(R.id.tvBuyerName)
    TextView tvBuyerName;
    @BindView(R.id.tvBuyerNoTitle)
    TextView tvBuyerNoTitle;
    @BindView(R.id.tvBuyerNo)
    TextView tvBuyerNo;
    @BindView(R.id.tvBuyerBankTitle)
    TextView tvBuyerBankTitle;
    @BindView(R.id.tvBuyerBank)
    TextView tvBuyerBank;
    @BindView(R.id.tvSupplierTitle)
    TextView tvSupplierTitle;
    @BindView(R.id.tvSupplierName)
    TextView tvSupplierName;
    @BindView(R.id.tvSupplierNoTitle)
    TextView tvSupplierNoTitle;
    @BindView(R.id.tvSupplierNoName)
    TextView tvSupplierNoName;
    @BindView(R.id.tvSupplierBankTitle)
    TextView tvSupplierBankTitle;
    @BindView(R.id.tvSupplierBankName)
    TextView tvSupplierBankName;
    @BindView(R.id.rvOrderDetail)
    RecyclerView rvOrderDetail;
    @BindView(R.id.llApproveTitle)
    LinearLayout llApproveTitle;
    @BindView(R.id.rvApprove)
    RecyclerView rvApprove;
    @BindView(R.id.ivImage)
    ImageView ivImage;
    @BindView(R.id.rlApproveEmpty)
    RelativeLayout rlApproveEmpty;
    @BindView(R.id.scrollContent)
    NiceNestedScrollView scrollContent;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;
    @BindView(R.id.ycLoading)
    YCLoadingView ycLoading;
    @BindView(R.id.rlClause)
    RelativeLayout rlClause;
    @BindView(R.id.ibToolbarMore)
    ImageButton ibToolbarMore;

    private String id;
    private static final String ID = "id";

    private List<OrderProductBean> mOrderProductBeans = new ArrayList<>();
    private PsDetailProductAdapter mPsDetailProductAdapter;

    private List<ContractCommentBean> mOrderCommentBeans = new ArrayList<>();
    private ContractCommentAdapter mPsDetailCommentAdapter;
    private String clause,mStatus;
    private EasyPopup mEasyPopup;

    public static void show(Activity activity,String id){
        Intent intent = new Intent(activity,ContractDetailActivity.class);
        intent.putExtra(ID,id);
        activity.startActivity(intent);
    }

    @Override
    protected void init() {
        if (null == getIntent() || !getIntent().hasExtra(ID)){
            finish();
        }else {
            id = getIntent().getStringExtra(ID);
        }
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_contract_detail;
    }

    @Override
    protected ContractDetailAtPresenter createPresenter() {
        return new ContractDetailAtPresenter(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvToolbarTitle.setText("采购合同详情");
        initAdapter();
    }

    private void initPopMenu() {
        mEasyPopup = EasyPopup.create()
                .setContext(this)
                .setContentView(R.layout.pop_menu_contract_more_detail)
                .setAnimationStyle(R.style.RightTop2PopAnim)
                .setOnViewListener((view, basePopup) -> {
                    TextView tvEdit =  view.findViewById(R.id.tvEdit);
                    TextView tvApprove = view.findViewById(R.id.tvApprove);
                    if (!ContractStatus.HAS_REJECT.getStatus().equals(mStatus)){
                        tvApprove.setVisibility(View.VISIBLE);
                    }else {
                        tvApprove.setVisibility(View.GONE);
                    }

                    tvEdit.setOnClickListener(v -> {
                        handleEditClick();
                        mEasyPopup.dismiss();
                    });

                    tvApprove.setOnClickListener(v -> {
                        handleApproveClick();
                        mEasyPopup.dismiss();
                    });
                })
                .setFocusAndOutsideEnable(true)
                .apply();
    }

    private void handleApproveClick() {
        ContractEnsureActivity.show(ContractDetailActivity.this,id);
    }

    private void handleEditClick() {
        ContractEditActivity.show(ContractDetailActivity.this,id);
    }

    private void setLoadingState(LoadingType loadingType){
        switch (loadingType){
            case LOADING:
                if (ycLoading.getVisibility() == View.GONE){
                    ycLoading.setVisibility(View.VISIBLE);
                }

                if (scrollContent.getVisibility() == View.VISIBLE){
                    scrollContent.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }

                if (llErrorNetwork.getVisibility() == View.VISIBLE){
                    llErrorNetwork.setVisibility(View.GONE);
                }
                break;
            case SUCCESS:

                if (ycLoading.getVisibility() == View.VISIBLE){
                    ycLoading.setVisibility(View.GONE);
                }

                if (scrollContent.getVisibility() == View.GONE){
                    scrollContent.setVisibility(View.VISIBLE);
                    bottom.setVisibility(View.VISIBLE);
                }


                if (llErrorNetwork.getVisibility() == View.VISIBLE){
                    llErrorNetwork.setVisibility(View.GONE);
                }
                break;
            case ERROR:
                if (ycLoading.getVisibility() == View.VISIBLE){
                    ycLoading.setVisibility(View.GONE);
                }

                if (scrollContent.getVisibility() == View.VISIBLE){
                    scrollContent.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }


                if (llErrorNetwork.getVisibility() == View.GONE){
                    llErrorNetwork.setVisibility(View.VISIBLE);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void initData() {
        setLoadingState(LoadingType.LOADING);
        mPresenter.queryContractDetail(id);
    }

    @Override
    protected void initListener() {
        rlClause.setOnClickListener(v -> {
            // 合同条款点击事件...
            ContractClauseActivity.show(ContractDetailActivity.this,clause);
        });

        ibToolbarMore.setOnClickListener(v -> showMenu(v));

        ivToolbarNavigation.setOnClickListener(v -> finish());
    }

    private void showMenu(View view) {
        int offsetX = DisplayHelper.dp2Px(20) - view.getWidth() / 2;
        int offsetY = (DisplayHelper.dp2Px(45) - view.getHeight()) / 2;
        mEasyPopup.showAtAnchorView(view, YGravity.BELOW, XGravity.ALIGN_RIGHT, offsetX, offsetY);
    }

    private void initAdapter(){
        // 设置商品的Adapter
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        rvOrderDetail.setHasFixedSize(true);
        rvOrderDetail.setNestedScrollingEnabled(false);
        rvOrderDetail.setLayoutManager(manager);
        rvOrderDetail.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, ScreenUtils.dip2px(this,0.5f), ContextCompat.getColor(this, R.color.borderColorBase)));
        mPsDetailProductAdapter = new PsDetailProductAdapter(R.layout.item_order_product_detail,mOrderProductBeans);
        rvOrderDetail.setAdapter(mPsDetailProductAdapter);

        // 设置评论的Adapter
        LinearLayoutManager managerComment = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        managerComment.setSmoothScrollbarEnabled(true);
        managerComment.setAutoMeasureEnabled(true);
        rvApprove.setHasFixedSize(true);
        rvApprove.setNestedScrollingEnabled(false);
        rvApprove.setLayoutManager(managerComment);
        rvApprove.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, ScreenUtils.dip2px(this,0.5f), ContextCompat.getColor(this, R.color.borderColorBase)));
        mPsDetailCommentAdapter = new ContractCommentAdapter(R.layout.item_order_comment_detail,mOrderCommentBeans);
        rvApprove.setAdapter(mPsDetailCommentAdapter);
    }

    @Override
    public void getContractDetailSuccess(ContractDetailResponse contractDetailResponse) {
        setLoadingState(LoadingType.SUCCESS);
        if (null != contractDetailResponse){

            // 设置标签
            tvTag.setText(contractDetailResponse.getStatusName());
            if (ContractStatus.HAS_PASS.getStatus().equals(contractDetailResponse.getStatus())){
                tvTag.setBackground(ResHelper.getDrawable(R.drawable.tag_order_pass));
            }else if (ContractStatus.HAS_REJECT.getStatus().equals(contractDetailResponse.getStatus())){
                tvTag.setBackground(ResHelper.getDrawable(R.drawable.tag_order_reject));
            }else if (ContractStatus.WAIT_SUBMIT.getStatus().equals(contractDetailResponse.getStatus())){
                tvTag.setBackground(ResHelper.getDrawable(R.drawable.tag_order_submit));
            }else {
                tvTag.setBackground(ResHelper.getDrawable(R.drawable.tag_order_default));
            }

            // 设置基本信息 用户等
            // 设置人-部门
            tvUserDept.setText(contractDetailResponse.getCreateName());
            // tag名
            tvTextSingleName.setText(contractDetailResponse.getCreateName().substring(0,1));
            // 创建时间
            tvCreateTime.setText(ResHelper.getString(R.string.order_detail_create_time, TimeUtil.getDayTime(contractDetailResponse.getCreateDate())));
            tvOrderContract.setText(contractDetailResponse.getInvoiceNo());
            tvBuyerName.setText(contractDetailResponse.getPurName());
            tvBuyerNo.setText(contractDetailResponse.getPurBankno());
            tvBuyerBank.setText(contractDetailResponse.getPurBank());
            tvSupplierName.setText(contractDetailResponse.getSupName());
            tvSupplierNoName.setText(contractDetailResponse.getSupBankno());
            tvSupplierBankName.setText(contractDetailResponse.getSupBank());

            // 底部商品数量以及价格
            String totalMoney = BigDecimalUtils.keep2Decimal(contractDetailResponse.getTotalMoney());
            int len = totalMoney.length();
            SpannableString spannableString = new SpannableString(
                    ResHelper.getString(R.string.down_order_sum,String.valueOf(contractDetailResponse.getProducts().size()),totalMoney));
            int totalLength = spannableString.length();
            spannableString.setSpan(new SpannableMoney(ContractDetailActivity.this),
                    totalLength-len-1,totalLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tvProductSum.setText(spannableString);
            // 合同明细
            if (contractDetailResponse.getProducts() != null){
                mOrderProductBeans.clear();
                mOrderProductBeans.addAll(contractDetailResponse.getProducts());
                mPsDetailProductAdapter.notifyDataSetChanged();
            }

            // 合同条款信息
            clause = contractDetailResponse.getCovenant();

            // 合同审批
            // 如果是待提交/待审批状态 那么是无评论表的
            if (ContractStatus.WAIT_SUBMIT.getStatus().equals(contractDetailResponse.getStatus()) ||
                    ContractStatus.WAIT_APPROVAL.getStatus().equals(contractDetailResponse.getStatus())){
                llApproveTitle.setVisibility(View.GONE);
                rvApprove.setVisibility(View.GONE);
                rlApproveEmpty.setVisibility(View.GONE);
            }else {
                llApproveTitle.setVisibility(View.VISIBLE);
                rvApprove.setVisibility(View.VISIBLE);
                // 如果为空或者是0 那么就显示空白页咯
                if (contractDetailResponse.getExamines() == null || contractDetailResponse.getExamines().size() == 0){
                    rlApproveEmpty.setVisibility(View.VISIBLE);
                }else {
                    rlApproveEmpty.setVisibility(View.GONE);
                    mOrderCommentBeans.addAll(contractDetailResponse.getExamines());
                    mPsDetailCommentAdapter.notifyDataSetChanged();
                }
            }

            mStatus = contractDetailResponse.getStatus();
            // 只有在待审批&已驳回的状态下右上角按钮是显示的状态
            if (contractDetailResponse.isFlag()){
                if (mStatus.equals(ContractStatus.WAIT_SUBMIT.getStatus())
                        || mStatus.equals(ContractStatus.HAS_REJECT.getStatus())){
                    ibToolbarMore.setVisibility(View.VISIBLE);
                }
            }
            initPopMenu();
        }
    }

    @Override
    public void getContractDetailFailure(String err) {
        setLoadingState(LoadingType.ERROR);
        UIUtils.showToast(err);
    }

}
